package com.hengpeng.itfin.tools;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;

import org.springframework.security.core.codec.Base64;

import com.hengpeng.common.util.MD5;

public class ReadFileUnGzipImpl implements ReadFile
{
	private String content;

	private String digest;

	private String inDigest;

	private String source;

	public ReadFileUnGzipImpl(String content, String digest) throws Exception
	{
		this.content = content;
		this.digest = digest;
		this.unGzip();
	}

	private void unGzip() throws Exception
	{
		byte[] buf = Base64.decode(content.getBytes("GBK"));
		ByteArrayInputStream im = new ByteArrayInputStream(buf);
		GZIPInputStream zis = new GZIPInputStream(im);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024];
		while ((len = zis.read(buffer)) != -1)
		{
			baos.write(buffer, 0, len);
		}
		zis.close();
		im.close();
		source = baos.toString("GBK");
		inDigest = MD5.encodeString(source, "GBK");
		source = source.replaceAll("[\\x00]", "");
		baos.close();
	}

	@Override
	public boolean verifyDigest()
	{
		return digest.equalsIgnoreCase(inDigest);
	}

	@Override
	public String digest()
	{
		return inDigest;
	}

	@Override
	public String read()
	{
		return source;
	}
}
